#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
打包脚本 - 将设备信息登记程序打包成单文件可执行程序
"""

import os
import sys
import subprocess

def check_pyinstaller():
    """检查PyInstaller是否已安装"""
    try:
        import PyInstaller
        print(f"PyInstaller版本: {PyInstaller.__version__}")
        return True
    except ImportError:
        print("PyInstaller未安装，正在安装...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
            print("PyInstaller安装成功！")
            return True
        except Exception as e:
            print(f"安装PyInstaller失败: {e}")
            return False

def check_icon():
    """检查图标文件是否存在"""
    icons = ['app_icon.ico', 'icon.ico']
    for icon in icons:
        if os.path.exists(icon):
            print(f"找到图标文件: {icon}")
            return icon
    print("警告: 未找到图标文件，将使用默认图标")
    return None

def build():
    """执行打包"""
    print("=" * 50)
    print("开始打包设备信息登记程序")
    print("=" * 50)
    
    # 检查PyInstaller
    if not check_pyinstaller():
        print("错误: 无法安装PyInstaller，打包失败")
        return False
    
    # 检查图标
    icon = check_icon()
    
    # 检查主程序文件
    if not os.path.exists('main.py'):
        print("错误: 未找到main.py文件")
        return False
    
    # 构建PyInstaller命令
    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--onefile",  # 单文件模式
        "--windowed",  # 无控制台窗口
        "--name", "设备信息登记",  # 可执行文件名称
        "--clean",  # 清理临时文件
        "--noconfirm",  # 覆盖输出目录
    ]
    
    # 添加图标
    if icon:
        cmd.extend(["--icon", icon])
    
    # 添加隐藏导入
    hidden_imports = [
        'cryptography',
        'cryptography.fernet',
        'pandas',
        'tkcalendar',
        'paramiko',
        '_cffi_backend',
    ]
    for imp in hidden_imports:
        cmd.extend(["--hidden-import", imp])
    
    # 添加主程序文件
    cmd.append('main.py')
    
    print("\n执行打包命令:")
    print(" ".join(cmd))
    print("\n" + "=" * 50)
    
    try:
        # 执行打包
        subprocess.check_call(cmd)
        print("\n" + "=" * 50)
        print("打包完成！")
        print(f"可执行文件位置: dist/设备信息登记.exe")
        print("=" * 50)
        return True
    except subprocess.CalledProcessError as e:
        print(f"\n错误: 打包失败，返回码: {e.returncode}")
        return False
    except Exception as e:
        print(f"\n错误: 打包过程中出现异常: {e}")
        return False

if __name__ == "__main__":
    success = build()
    if not success:
        sys.exit(1)

